using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using DatabaseBackup.Models;

namespace DatabaseBackup.Services
{
    /// <summary>
    /// MySQL数据库备份服务
    /// </summary>
    public class MySqlBackupService : IBackupService<MySqlDatabaseConfig>
    {
        /// <summary>
        /// 执行MySQL数据库备份
        /// </summary>
        public async Task<bool> BackupAsync(MySqlDatabaseConfig config, string backupPath)
        {
            try
            {
                // 确保备份目录存在
                Directory.CreateDirectory(backupPath);

                // 生成备份文件名
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                string fileName = $"{config.DatabaseName}_{timestamp}.sql";
                string filePath = Path.Combine(backupPath, fileName);

                // 构建mysqldump命令
                string arguments = $"--host={config.Server} --port={config.Port} --user={config.Username} --password={config.Password} --databases {config.DatabaseName} --result-file=\"{filePath}\"";

                // 执行mysqldump命令
                using (var process = new Process())
                {
                    process.StartInfo.FileName = "mysqldump.exe";
                    process.StartInfo.Arguments = arguments;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.CreateNoWindow = true;

                    process.Start();

                    // 读取输出和错误信息
                    string output = await process.StandardOutput.ReadToEndAsync();
                    string error = await process.StandardError.ReadToEndAsync();

                    await process.WaitForExitAsync();

                    if (process.ExitCode != 0)
                    {
                        Console.WriteLine($"MySQL备份失败 ({config.DatabaseName}): {error}");
                        return false;
                    }
                }

                Console.WriteLine($"MySQL备份成功: {filePath}");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"MySQL备份出错 ({config.DatabaseName}): {ex.Message}");
                return false;
            }
        }
    }
}
